<script setup lang="ts">
import { useUserStore } from "@/store/userStore";
import {
  SettingOutlined,
  FullscreenOutlined,
  FullscreenExitOutlined
} from "@ant-design/icons-vue";
import { Router } from "vue-router";
import { LogoutRes, logout } from '@/api/security'
import Cookies from 'js-cookie'
import { message } from 'ant-design-vue'
import { fullscreen, cancelFullscreen } from '@/utils/jsUtil'
import { resetRoute } from '@/router/index'
import Fuse from 'fuse.js'
import { useMenuStore } from '@/store/menuStore'

const userPopup = ref<boolean | undefined>(false);
const router: Router = useRouter();
const userStore = useUserStore()
const isFullScreen = ref<boolean>(false)
const settingRightBarRef = ref()
const menuStore = useMenuStore()

const handleLogout = async () => {
  //退出登录
  try {
    const { data: res }: { data: LogoutRes } = await logout() as any
    if (res.code == 200) {
      Cookies.remove('accessToken')
      userStore.accessToken = ''
      userStore.sysUser = {}
      localStorage.removeItem('dynamicTags')
      message.success('已退出')
      resetRoute()
    }
  } catch (error) {
    console.error(error);
  } finally {
    router.push('/login')
  }
};

const handleEnterProfile = () => {
  //不包含个人中心，则添加
  if (!menuStore.dynamicTagList.reduce((pre: string[], cur: any) => {
    pre.push(cur.key)
    return pre
  }, []).includes('/profile')) {
    menuStore.dynamicTagList.push({
      title: '个人中心',
      key: '/profile',
      enableClose: true,
      isActive: false,
    })
    menuStore.saveDynamicTag2Local();
  }
  userPopup.value = false
  router.push('/profile')
}

//全屏处理
const handleFullScreen = () => {
  if (document.fullscreenElement === null) {
    fullscreen(document.documentElement)
    isFullScreen.value = true
  } else {
    cancelFullscreen()
    isFullScreen.value = false
  }
}

//设置
const openSettingModal = () => {
  settingRightBarRef.value.openSettingModal()
}

//搜索部分
const searchContent = ref<string>('')
const isSearch = ref<boolean>(false)
const searchList = ref<any[]>([])
const handleSearch = () => {
  searchList.value = new Fuse(router.getRoutes(), {
    includeScore: true,
    shouldSort: true,
    includeMatches: true,
    threshold: 0.4,
    location: 0,
    distance: 100,
    minMatchCharLength: 1,
    keys: [
      "path",
      "name",
      "meta.title",
    ]
  }).search(searchContent.value)
}

const enterRoute = (item: any) => {
  router.push(item.path)
  menuStore.addDynamicTag({
    title: item.name,
    key: item.path,
    enableClose: true,
    isActive: true,
  });
  menuStore.toggleDynamicTag(item.path)
}
</script>

<template>
  <div class="flex items-center sm:justify-end sm:flex-1 h-[48px]">
    <div class="relative flex items-center justify-center w-[200px] h-full max-sm:hidden">
      <!-- 搜索框 -->
      <a-input v-model:value="searchContent" placeholder="输入搜索内容" @change="handleSearch" :bordered="false" allow-clear
        @focus="isSearch = true" @blur="isSearch = false">
      </a-input>
      <Transition name="vue">
        <div class="absolute z-20 w-[280px] right-0 top-[50px] bg-white border dark:bg-darkBg 
        dark:text-white rounded-md shadow-md min-h-[200px] max-h-[300px] overflow-y-auto"
          v-show="searchList.length !== 0 && isSearch">
          <a-list item-layout="horizontal" :data-source="searchList">
            <template #renderItem="{ item }">
              <a-list-item class="cursor-pointer hover:bg-gray-50" @click="enterRoute(item.item)">
                <a-list-item-meta :description="item.item.path">
                  <template #title>
                    <p>{{ item.item.name }}</p>
                  </template>
                </a-list-item-meta>
              </a-list-item>
            </template>
          </a-list>
        </div>
      </Transition>
    </div>
    <div class="flex items-center justify-center w-10 h-full cursor-pointer hover:bg-slate-100 group"
      @click="handleFullScreen">
      <FullscreenOutlined v-show="!isFullScreen"
        class="flex items-center w-5 h-5 text-lg dark:text-white dark:group-hover:text-black" />
      <FullscreenExitOutlined v-show="isFullScreen"
        class="flex items-center w-5 h-5 text-lg dark:text-white dark:group-hover:text-black" />
    </div>
    <div class="flex items-center justify-center w-10 h-full cursor-pointer hover:bg-slate-100 group"
      @click="openSettingModal">
      <SettingOutlined class="flex items-center w-5 h-5 text-lg dark:text-white dark:group-hover:text-black" />
    </div>
    <div class="flex items-center justify-center h-full cursor-pointer w-28 hover:bg-slate-100 group">
      <a-popover v-model:open="userPopup" trigger="click" placement="bottomRight">
        <template #content>
          <div class="w-full">
            <div class="flex items-center w-full h-8 text-sm text-center cursor-pointer hover:text-primary"
              @click="handleEnterProfile">
              个人中心
            </div>
            <div class="flex items-center w-full h-8 text-sm text-center cursor-pointer hover:text-primary"
              @click="handleLogout">
              退出登录
            </div>
          </div>
        </template>
        <div class="flex items-center">
          <div class="mr-4 overflow-hidden text-sm dark:text-white max-w-16 text-ellipsis dark:group-hover:text-black">
            {{ userStore.sysUser.userName || '' }}
          </div>
          <a-avatar :size="32" class="flex items-center justify-center cursor-pointer select-none bg-primary-2"
            :src="userStore.sysUser.avatar">
          </a-avatar>
        </div>
      </a-popover>
    </div>
    <SettingRightBar ref="settingRightBarRef" />
  </div>
</template>

<style scoped>
.vue-enter-active {
  animation: dh ease-in .3s;
}

.vue-leave-active {
  animation: dh ease-in .3s reverse;
}

@keyframes dh {
  0% {
    transform: translateY(-10px);
    opacity: 0;
  }

  100% {
    transform: translateY(0px);
    opacity: 1;
  }
}
</style>
